<template>
    <div>
        <el-page-header icon="" content="创建新闻" title="新闻管理"></el-page-header>

        <el-form ref="newsFormRef" status-icon :model="newsForm" :rules="newsFormRules" label-width="auto"
            class="demo-ruleForm">

            <el-form-item label="标题" prop="title">
                <el-input v-model="newsForm.title" />
            </el-form-item>

            <el-form-item label="内容" prop="content">
                <editor @event="handleChange"></editor>
            </el-form-item>

            <el-form-item label="类别" prop="category">
                <el-select v-model="newsForm.category" style="width: 150px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="封面" prop="cover">
                <Upload :avatar = "newsForm.cover" @fileChange="avatarChange"></Upload>
            </el-form-item>

            <el-form-item class="label">
                <el-button type="primary" @click="submitForm()" style="margin: 0 auto;">添加新闻</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive} from 'vue'
import {useRouter} from 'vue-router'
import editor from '@/components/editor/Editor.vue';
import Upload from '@/components/upload/Upload.vue';
import upload from '@/util/upload'
import axios from 'axios';

const router = useRouter()
const newsFormRef = ref()
const newsForm = reactive({
    title: "",
    content: "",
    category: 1,
    cover: "",
    file: null,
    isPublish: 0
})

const handleChange = (data) => {
    // console.log(data)
    newsForm.content = data
}

const avatarChange = (file) =>{
    newsForm.cover = URL.createObjectURL(file)
    newsForm.file = file
} 

const submitForm = ()=>{
    newsFormRef.value.validate(async (valid)=>{
        if(valid){
            await upload("/adminapi/news/add",newsForm)
            router.push('/news-manage/newslist')
        }
    })
}

const newsFormRules = reactive({
    title: [
        { required: true, message: '输入标题', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '输入内容', trigger: 'blur' },
    ],
    category: [
        { required: true, message: '选择分类', trigger: 'blur' },
    ],
    cover: [
        { required: true, message: '上传图片', trigger: 'blur' },
    ]
})

const options = [
    {
        label:"最新动态",
        value:1
    },
    {
        label:"典型案例",
        value:2
    },
    {
        label:"通知公告",
        value:3
    }
]
</script>

<style scoped>
.demo-ruleForm {
    margin-top: 50px;
}
</style>